package org.zjt.thread.interrupt;

import lombok.extern.slf4j.Slf4j;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.*;


/**
 * Description:
 *
 * @author juntao.zhang
 * Date: 2018-05-31 下午3:45
 * @see
 */
@Slf4j
public class ThreadPoolManager {

    private static final ExecutorService EXECUTORSERVICE = Executors.newFixedThreadPool(10);

    private static final Map<Future,InterruptableOperation> INTERRUPTABLEOPERATION_MAP = new ConcurrentHashMap<>();

    private static final ScheduledThreadPoolExecutor MONITOR = new ScheduledThreadPoolExecutor(1);



    public ThreadPoolManager(){
        MONITOR.scheduleAtFixedRate(()->{
            for (Iterator<Map.Entry<Future, InterruptableOperation>> it = INTERRUPTABLEOPERATION_MAP.entrySet().iterator(); it.hasNext();){
                Map.Entry<Future, InterruptableOperation> entry = it.next();
                InterruptableOperation operation = entry.getValue();
                LocalDateTime start = operation.getStart();
                long millis = Duration.between(start, LocalDateTime.now()).toMillis();
                Future future = entry.getKey();
                if(millis > 1000 && !future.isDone() && !future.isCancelled()){
                    future.cancel(Boolean.TRUE);
                    it.remove();
                }
                if (future.isDone() || future.isCancelled()){
                    it.remove();
                }
            }
        },0,1, TimeUnit.SECONDS);
    }


    public Future<String> submit(InterruptableOperation InterruptableOperation) {
        Future<String> submit = EXECUTORSERVICE.submit(InterruptableOperation);
        INTERRUPTABLEOPERATION_MAP.put(submit, InterruptableOperation);
        return submit;
    }


}
